/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Generador;

import BitlyAlgo.Shortener;
import SeparadorUrls.Utility;
import bitly.BitlyUrl;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Demon
 */
public class Generador {

    public String shortUrl;
    public URL completeUrl;
    public String path;
    private LinkedList<Integer> mapeo;
    public boolean isUnsigned;
    byte[] md5;
    public BitlyUrl bUrl;

    /**
     * 
     * @param u
     */
    public Generador() {
        path = null;
        shortUrl = null;
        completeUrl = null;
        mapeo = new LinkedList<Integer>();
        isUnsigned = false;
        md5 = null;
        bUrl = null;

    }

    public void mainWorker(String url){
        this.setURL(url);
        this.setPath();
        this.setMD5();

        Shortener sh = new Shortener();
        System.out.println("MD5: "+this.md5toLong());
        sh.compress(this.md5toLong());
        sh.printArray(sh.array);
        sh.match();
        System.out.println("Compresor: "+sh.shortestURL);
        sh.auxDecompress(sh.shortestURL);
       // System.out.println(sh.decompress(sh.shortestURL));

        System.out.println(bUrl.getFinallUrl(sh.shortestURL));
        
    }

    /**
     *
     * @param strUrl
     */
    private void setURL(String strUrl) {
        this.completeUrl = Utility.regresaURL(strUrl);

    }

    /**
     *
     */
    private void setPath() {
        if (this.completeUrl != null) {
            this.path = this.completeUrl.getPath();
            this.bUrl = new BitlyUrl(completeUrl);

        } else {
            System.out.println("URL NO VALIDA POR EL SISTEMA :( ");
            System.exit(1);
        }

    }

    /**
     *
     * @param path
     * @return
     */
    private void setMD5() {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.reset();
            md.update(this.path.getBytes());
            this.md5 = md.digest();

        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(Generador.class.getName()).log(Level.SEVERE, null, ex);
            System.exit(1);
        }

    }

    /**
     * 
     * @return
     */
    private long md5toLong() {

        long value = 0;
        for (int i = 0; i < md5.length; i++) {
            value += ((long) md5[i] & 0xffL) << (8 * i);  //byte 8 bits recorrer el arreglo 
        }

        if (value < 0) {
            value *= -1;
            isUnsigned = false;
        }
        return value;
    }
   
}
